package com.hue.controller;


import com.hue.entity.JwtUtils;
import com.hue.entity.R;
import com.hue.entity.UcenterMember;
import com.hue.entity.vo.RegisterVo;
import com.hue.service.UcenterMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 姚凤桥
 * @since 2021-07-05
 */
@RestController
@CrossOrigin
@RequestMapping("/ucenter-member")
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    /*
        登录
     */
    @PostMapping("/login")
    public R login(@RequestBody UcenterMember ucenterMember) {
        //登录，并返回token
        String token = ucenterMemberService.login(ucenterMember);
        return token != null ? R.ok().data("token", token) : R.error().data("error", "用户名或密码错误!");
    }

    /*
        注册
     */
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo) {
        Map<String, String> map = ucenterMemberService.register(registerVo);
        //注册失败
        if (map.get("error") != null) {
            return R.error().data("error", map.get("error"));
        }
        //注册成功
        return R.ok().data("success", map.get("success"));
    }

    /*
        请求验证码
     */
    @GetMapping("/getCheckCode/{to}")
    public R getCheckCode(@PathVariable("to") String to) {
        //发送验证码
        Map<String, String> map = ucenterMemberService.sendCheckCode(to);
        //发送失败
        if (map.get("error") != null) {
            return R.error().data("error", map.get("error"));
        }
        //发送成功
        return R.ok().data("success", map.get("success"));
    }

    /*
        根据token获取用户信息
     */
    @GetMapping("/getUserInfo")
    public R getUserInfo(HttpServletRequest request){
        //根据token获取用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //根据id查询用户信息
        UcenterMember user = ucenterMemberService.getById(id);
        return R.ok().data("user",user);
    }
}

